/*
 * Copyright Radosław Smogura, 2012. All rights reserved.
 *
 * The content of this file is confidential and it is intelectual property
 * of copyright owners.
 * 
 *
 * $URL: http://reprap-ide.googlecode.com/svn/trunk/RepRapIDE/RepRapProject/src/main/java/eu/softper/reprap/project/nodes/actions/AddStlFileAction.java $
 * $Id: AddStlFileAction.java 3 2012-11-19 10:58:30Z mail@smogura.eu $
 * $Revision: 3 $
 */
package eu.softper.reprap.project.nodes.actions;

import eu.softper.reprap.project.RepRapProject;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.openide.loaders.DataFolder;
import org.openide.nodes.Node;
import org.openide.util.HelpCtx;
import org.openide.util.actions.NodeAction;
import org.openide.windows.WindowManager;

/** Actions uses 
 *
 * @author Radosław Smogura
 */
public class AddStlFileAction extends NodeAction {
    private static AddStlFileAction instance;
    
    private static File lastOpenedDirectory;
    private FileNameExtensionFilter stlFilesFilter = new FileNameExtensionFilter("STL Files", "stl");
    
    public AddStlFileAction() {
        
    }
    
    @Override
    protected boolean asynchronous() {
        return false;
    }
    
    @Override
    protected void performAction(Node[] activatedNodes) {
        assert activatedNodes.length == 1;
        
        final DataFolder folder = activatedNodes[0].getLookup().lookup(DataFolder.class);
        final RepRapProject project = activatedNodes[0].getLookup().lookup(RepRapProject.class);
        
        JFileChooser fileChooser = new JFileChooser();
        if (lastOpenedDirectory != null)
            fileChooser.setCurrentDirectory(lastOpenedDirectory);
        fileChooser.setFileFilter(stlFilesFilter);
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fileChooser.setMultiSelectionEnabled(true);
        if (fileChooser.showDialog(WindowManager.getDefault().getMainWindow(), null) == JFileChooser.APPROVE_OPTION) {
            File[] files = fileChooser.getSelectedFiles();
            if (files != null && files.length != 0) {
                lastOpenedDirectory = files[0].getParentFile();
            }
            project.addFilesToProject(files, folder.getPrimaryFile());
        }
    }

    @Override
    protected boolean enable(Node[] activatedNodes) {
        return activatedNodes.length == 1 && activatedNodes[0].getLookup().lookup(DataFolder.class) != null;
    }

    @Override
    public String getName() {
        return "Add STL file...";
    }

    @Override
    public HelpCtx getHelpCtx() {
        return null;
    }

    public static AddStlFileAction getInstance() {
        if (instance == null)
            instance = new AddStlFileAction();
        return instance;
    }
}
